package com.learn.lb.mapred;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author laibo
 * @since 2019/7/1 21:44
 * <p> 单词统计
 */
public class WordCount {

    private static Logger logger = LoggerFactory.getLogger(WordCount.class);

    public static class Map extends Mapper<LongWritable, Text, Text, LongWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split(" ");
            for (String s : split) {
                //mapper之后装换成<K, 1>，mapper不合并
                context.write(new Text(s), new LongWritable(1));
            }
        }
    }

    public static class Reduce extends Reducer<Text, LongWritable, Text, LongWritable> {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                sum += value.get();
            }
            context.write(key, new LongWritable(sum));
        }
    }

    public static void main(String[] args) throws Exception {
        logger.info("开始运行mapreducer任务.....");
        Configuration hdfsConfiguration = new Configuration();
        Path dstPath = new Path("/wc_in/data");
        Path outPath = new Path("/wc_out");
        GenerateMapReducerUtils.buildJobBefore(hdfsConfiguration, "wc.txt", dstPath, outPath);
        logger.info("开始进行MapReducer计算....");
        Job job = Job.getInstance(hdfsConfiguration, "Data Deduplication");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);
        //设置输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        //设置输出目录
        FileInputFormat.addInputPath(job, dstPath);
        FileOutputFormat.setOutputPath(job, outPath);
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
